//system
#include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_log.h>
#include "esp_netif.h"
#include "esp_ota_ops.h"
//drivers
#include "Drivers/uart_drv.h"
#include "Drivers/nvs_drv.h"
#include "Drivers/wifi_drv.h"
#include "Drivers/smartconfig_wifi.h"
#include "Drivers/tcp_drv.h"
#include "Drivers/spiffs_drv.h"
#include "Drivers/sntp_time_drv.h"
//apps
#include "App/uart_data.h"
#include "App/uart_console.h"
#include "App/sn_handle.h"
#include "App/ota_task.h"
#include "App/udp_recipe_fetch.h"

#include "tools.h"

#define TAG   "main"

void app_main(void)
{
    nvs_flash_init();           //初始化nvs
    esp_netif_init();           //初始化网络接口
    UartDataInit();             //初始化数据串口
    SpiffsInit();               //初始化文件系统
    
    xTaskCreate(UartConsoleRecvTask,
                 "uart_console_recv_task", 4096, NULL, 1, NULL);                                //开启调试串口接收任务

    xTaskCreate(SnHandleTask,        
                "sn_handle_task", 4096, NULL, 2, NULL);                                         //开启sn处理任务

    xEventGroupWaitBits(SnEventGroup, SN_EXIST_BIT, true, true, portMAX_DELAY);                 //等待sn处理完成    

    xTaskCreate(UartDataRecvTask, 
                "uart_data_recv_task", 4096 * 2, NULL, 3, NULL);                                //开启数据串口接收任务

    ConnectToWifi();                                //连接wifi
    xEventGroupWaitBits(WifiEventGroup, WIFI_CONNECTED_BIT, false, false, portMAX_DELAY);       //等待wifi连接成功

    xTaskCreate(OTA_Task, 
          "ota_task", 4096, NULL, 10, NULL);        //开启ota任务
    xEventGroupWaitBits(OTAEventGroup, OTA_EXIT_BIT, true, true, portMAX_DELAY);                //等待ota任务完成

    xTaskCreate(recipeFetchTask, 
                "recipe_fetch_task", 4096, NULL, 4, NULL);                                      //开启获取菜谱任务
    
    esp_ota_mark_app_valid_cancel_rollback();       //升级完成，取消回滚
    
    SntpTimeDrvInit();                              //初始化NTP更新时间
}
